﻿using System;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace Ooaavee.TestTools
{
    /// <summary>
    /// Provides an access to a project configuration file.
    /// </summary>
    internal static class ConfigurationManager
    {
        private static TestToolsConfiguration _instance;

        /// <summary>
        /// Gets configurations (see Ooaavee.TestTools.xml).
        /// </summary>
        internal static TestToolsConfiguration Instance
        {
            get { return _instance ?? (_instance = ReadConfiguration(Path)); }
        }

        /// <summary>
        /// Configuration file path.
        /// </summary>
        internal static string Path
        {
            get
            {
                string assemblyPath = Assembly.GetExecutingAssembly().Location;
                string path = string.Format(@"{0}\Ooaavee.TestTools.xml", new FileInfo(assemblyPath).DirectoryName);
                return path;
            }
        }

        /// <summary>
        /// Reads the configuration file from the specified path.
        /// </summary>
        /// <param name="path">configuration file path</param>
        /// <returns>configurations</returns>
        private static TestToolsConfiguration ReadConfiguration(string path)
        {
            if (File.Exists(path) == false)
            {
                throw new TestToolsException(String.Format("Could not find the configuration file {0}.", path));
            }

            TestToolsConfiguration configuration;
            XmlSerializer serializer = new XmlSerializer(typeof (TestToolsConfiguration));
            using (TextReader reader = new StreamReader(path))
            {
                configuration = (TestToolsConfiguration)serializer.Deserialize(reader);
                reader.Close();
            }
            return configuration;
        }
    }
}